#include "devicedialog.h"
#include "ui_devicedialog.h"
#include <QRegExpValidator>

DeviceDialog::DeviceDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DeviceDialog)
{
    ui->setupUi(this);
    setWindowTitle(tr("设备信息"));  // 使用tr()方便国际化
    setFixedSize(size());

    // 初始化下拉框
    QStringList deviceTypes = {tr("传感器"), tr("控制器"), tr("执行器"), tr("网关"), tr("其他")};
    QStringList statusTypes = {tr("在线"), tr("故障"), tr("离线")};

    ui->comboBoxType->addItems(deviceTypes);
    ui->comboBoxStatus->addItems(statusTypes);

    // 设置日期范围和默认值
    ui->dateEditInstallation->setDateRange(QDate(2000, 1, 1), QDate::currentDate());
    ui->dateEditInstallation->setDate(QDate::currentDate());

    // 添加输入验证
    QRegExp nameRegex("^[\\w\\s\\-\\(\\)\\u4e00-\\u9fa5]{1,50}$"); // 允许中英文、数字、下划线等
    ui->lineEditName->setValidator(new QRegExpValidator(nameRegex, this));

    // 连接按钮信号
    connect(ui->btnSave, &QPushButton::clicked, this, &QDialog::accept);
    connect(ui->btnCancel, &QPushButton::clicked, this, &QDialog::reject);
}

DeviceDialog::~DeviceDialog()
{
    delete ui;
}

// Getter 实现
QString DeviceDialog::getDeviceName() const { return ui->lineEditName->text().trimmed(); }
QString DeviceDialog::getDeviceType() const { return ui->comboBoxType->currentText(); }
QString DeviceDialog::getLocation() const { return ui->lineEditLocation->text().trimmed(); }
QString DeviceDialog::getManufacturer() const { return ui->lineEditManufacturer->text().trimmed(); }
QString DeviceDialog::getModel() const { return ui->lineEditModel->text().trimmed(); }
QString DeviceDialog::getStatus() const { return ui->comboBoxStatus->currentText(); }
QDate DeviceDialog::getInstallationDate() const { return ui->dateEditInstallation->date(); }
QString DeviceDialog::getDescription() const { return ui->textEditDescription->toPlainText().trimmed(); }

// Setter 实现
void DeviceDialog::setDeviceName(const QString &name) { ui->lineEditName->setText(name); }
void DeviceDialog::setDeviceType(const QString &type) {
    int index = ui->comboBoxType->findText(type);
    ui->comboBoxType->setCurrentIndex(index >= 0 ? index : 0);
}
void DeviceDialog::setLocation(const QString &location) { ui->lineEditLocation->setText(location); }
void DeviceDialog::setManufacturer(const QString &manufacturer) { ui->lineEditManufacturer->setText(manufacturer); }
void DeviceDialog::setModel(const QString &model) { ui->lineEditModel->setText(model); }
void DeviceDialog::setStatus(const QString &status) {
    int index = ui->comboBoxStatus->findText(status);
    ui->comboBoxStatus->setCurrentIndex(index >= 0 ? index : 0);
}
void DeviceDialog::setInstallationDate(const QDate &date) { ui->dateEditInstallation->setDate(date); }
void DeviceDialog::setDescription(const QString &desc) { ui->textEditDescription->setPlainText(desc); }
